<!--
 * @Author: ChunLai
 * @Date: 2022-09-21 18:05:26
 * @LastEditTime: 2025-11-27 16:04:14
 * @Description: 被保人对象
 * @FilePath: \01.latest-short-insure\src\views\form\components\AssuredItem.vue
-->
<template>
  <div class="newModel" :class="bbrList.length == 1 ? 'mt10' : ''">
    <!-- 用户类型 holderType-->
    <div class="of_hid">
      <div class="topSec" v-if="bbrList.length > 1">
        <div class="flex_ac ft14">
          被保险人{{ pindex + 1 }}
          <span
            :class="enfold ? 'ms-row2-icon' : 'ms-row-icon'"
            style="margin-left: 8px"
            @click="enfold = !enfold"
            v-if="userInfo.relationToAppnt !== '4'"
          ></span>
        </div>
        <MsImgIcon
          name="delete"
          class="ml20"
          size="18"
          @click.native="delUserItem"
        />
      </div>
      <van-field
        label="为谁投保"
        :class="`bbr${pindex}_relationToAppnt`"
        :input-align="inputAlign"
        @click="
          showPopAction(
            'picker',
            'relationToAppnt',
            tbgxList,
            userInfo.relationToAppnt
          )
        "
        :value="userInfo.relationToAppntName"
        readonly
        placeholder="请选择"
        @focus="tipsInfo.relationToAppnt = ''"
        :error-message="tipsInfo.relationToAppnt"
        :error-message-align="inputAlign"
      >
        <span
          class="ms-row-icon"
          slot="right-icon"
          v-if="tbgxList.length > 0"
        ></span>
      </van-field>
      <div :key="`bbr${pindex}mode1`" v-if="userInfo.relationToAppnt !== '4'">
        <!-- 姓名 name-->
        <van-field
          label="姓名"
          :class="`bbr${pindex}_name`"
          v-model="userInfo.name"
          :input-align="inputAlign"
          clearable
          placeholder="请输入"
          :error-message="tipsInfo.name"
          @input="tipsInfo.name = ''"
          @blur="validInfo('name')"
          :error-message-align="inputAlign"
        >
        </van-field>
        <div class="enfold-line" :key="`bbr${pindex}mode3`" v-show="enfold">
          <van-field
            label="证件类型"
            :class="`bbr${pindex}_idType`"
            @click="
              showPopAction('picker', 'idType', idTypeList, userInfo.idType)
            "
            :value="userInfo.idName"
            readonly
            placeholder="请选择"
            :input-align="inputAlign"
            v-if="infoReg.hasOwnProperty('idType')"
            @focus="tipsInfo.idType = ''"
            :error-message="tipsInfo.idType"
            :error-message-align="inputAlign"
          >
            <span
              class="ms-row-icon"
              slot="right-icon"
              v-if="idTypeList.length > 1"
            ></span>
          </van-field>
          <!-- 证件号码 idNum-->
          <van-field
            label="证件号码"
            :class="`bbr${pindex}_idNum`"
            :input-align="inputAlign"
            v-model="cpCompute"
            clearable
            placeholder="请输入"
            :error-message="tipsInfo.idNum"
            @click="tipsInfo.idNum = ''"
            @focus="foI = true"
            @blur="
              foI = false;
              validInfo('idNum');
            "
            :error-message-align="inputAlign"
          >
            <MsImgIcon
              name="camera_l"
              size="22"
              slot="button"
              @click.native="showSheet = true"
            />
          </van-field>
          <!-- 性别 -->
          <van-field
            label="性别"
            :class="`bbr${pindex}_sex`"
            class="btn_pad3"
            :input-align="inputAlign"
          >
            <div slot="input">
              <span class="btn_text" v-if="disabledSex">
                {{ userInfo.sexName || "男" }}
              </span>
              <MsRadio
                v-else
                :curVal="userInfo.sex"
                btnType="sex"
                labelName="text"
                valueName="keyId"
                :arrList="sexList"
                @clickEvent="changeSexClick"
              />
            </div>
          </van-field>
          <van-field
            label="出生日期"
            :class="`bbr${pindex}_birthDate`"
            @click-input="showPopAction('date', 'birthDate', [])"
            placeholder="请选择"
            :input-align="inputAlign"
            @focus="tipsInfo.birthDate = ''"
            :error-message="tipsInfo.birthDate"
            :error-message-align="inputAlign"
          >
            <div class="age-box" slot="input">
              <span v-if="userInfo.birthDate"
                >{{ userInfo.birthDate }} ( {{ ageVal }}周岁 )
              </span>
              <span v-else style="color: #999">请选择</span>
            </div>
            <span
              class="ms-row-icon"
              slot="right-icon"
              v-if="!disabledSex"
            ></span>
          </van-field>
          <!-- 证件有效期 -->
          <van-field
            class="set_flex1 bbr_sex btn_pad3"
            v-if="infoReg.hasOwnProperty('validDateEnd')"
            :input-align="inputAlign"
          >
            <div slot="label" class="userSelect">
              <span>证件有效期</span>
              <FieldDescMode field="validDateEnd" />
            </div>
            <div slot="input">
              <MsRadio
                :curVal="longTime !== userInfo.validDateEnd"
                btnType="validDateEnd"
                labelName="text"
                valueName="keyId"
                flexName="mag0"
                :arrList="[
                  { text: '长期', keyId: false },
                  { text: '非长期', keyId: true },
                ]"
                @clickEvent="sameToLongTime"
              />
            </div>
          </van-field>
          <van-field
            label="有效期起期"
            :class="`bbr${pindex}_validDate`"
            @click="showPopAction('date', 'validDate', [])"
            :value="userInfo.validDate"
            readonly
            placeholder="请选择"
            @focus="tipsInfo.validDate = ''"
            :error-message="tipsInfo.validDate"
            :error-message-align="inputAlign"
            :input-align="inputAlign"
            v-if="infoReg.hasOwnProperty('validDate')"
          >
            <span class="ms-row-icon" slot="right-icon"></span>
          </van-field>
          <van-field
            label="有效期止期"
            :class="`bbr${pindex}_validDateEnd`"
            @click-input="showPopAction('date', 'validDateEnd', [])"
            :value="
              userInfo.validDateEnd == longTime ? '长期' : userInfo.validDateEnd
            "
            readonly
            placeholder="请选择"
            @focus="tipsInfo.validDateEnd = ''"
            :error-message="tipsInfo.validDateEnd"
            :error-message-align="inputAlign"
            :input-align="inputAlign"
            v-if="
              infoReg.hasOwnProperty('validDateEnd') &&
              (longTime !== userInfo.validDateEnd || !showLonger)
            "
          >
            <span
              class="ms-row-icon"
              slot="right-icon"
              v-if="!validDateDisabled"
            ></span>
          </van-field>
          <van-field
            label="国籍"
            :input-align="inputAlign"
            class="refnationality"
            @click="
              tipsInfo.nationality = '';
              showPopAction(
                'picker',
                'nationality',
                nationList,
                userInfo.nationality
              );
            "
            :value="userInfo.nationalityName"
            readonly
            placeholder="请选择"
            :error="tipsInfo.nationality !== ''"
            v-if="infoReg.hasOwnProperty('nationality')"
          >
            <span
              class="ms-row-icon"
              slot="right-icon"
              v-if="nationList.length > 1"
            ></span>
          </van-field>
          <!-- 现居地址 -->
          <van-field
            :input-align="inputAlign"
            v-if="infoReg.hasOwnProperty('areaName')"
            @click="showPopAction('address', 'areaName', [])"
            :value="userInfo.areaName"
            label="现居地址"
            type="textarea"
            rows="1"
            autosize
            readonly
            placeholder="请选择"
            label-width="170px"
            @focus="tipsInfo.areaName = ''"
            :error-message="tipsInfo.areaName"
            :error-message-align="inputAlign"
          >
            <div slot="label" class="flexlabel">
              <span class="mr5">现居地址</span>
              <div
                class="same_to_btn"
                :class="sameAppntForAreaAddr ? 'is_same_res' : ''"
                @click.stop="sameToAppnt($event, 'areaName')"
              >
                同投保人
              </div>
            </div>
            <span class="ms-row-icon" slot="right-icon"></span>
          </van-field>
          <van-field
            :input-align="inputAlign"
            :class="`bbr${pindex}_permanentAddress`"
            v-if="infoReg.hasOwnProperty('permanentAddress')"
            v-model="userInfo.permanentAddress"
            label="详细地址"
            type="textarea"
            rows="1"
            maxlength="30"
            autosize
            clearable
            :placeholder="
              detailAddrRule ? `必须包含:${detailAddrRule}` : '请输入'
            "
            @input="tipsInfo.permanentAddress = ''"
            @blur="validInfo('address')"
            :error-message="tipsInfo.permanentAddress"
            :error-message-align="inputAlign"
          />
          <!-- 手机号 phone-->
          <van-field
            label="手机号码"
            :class="`bbr${pindex}_phone`"
            v-model="userInfo.phone"
            type="number"
            maxlength="11"
            clearable
            placeholder="请输入"
            @focus="
              foI2 = true;
              tipsInfo.phone = '';
            "
            @blur="foI2 = false"
            :error-message="tipsInfo.phone"
            :input-align="inputAlign"
            :error-message-align="inputAlign"
            v-if="infoReg.hasOwnProperty('phone')"
            label-width="170px"
          >
            <div slot="label" class="flexlabel">
              <span class="mr5">手机号码</span>
              <div
                class="same_to_btn"
                :class="sameAppntForPhone ? 'is_same_res' : ''"
                @click.stop="sameToAppnt($event, 'phone')"
              >
                同投保人
              </div>
            </div>
          </van-field>
          <!--注意获取验证吗的时机-->
          <van-field
            class="phone_code_md"
            :input-align="inputAlign"
            v-if="infoReg.hasOwnProperty('validCode')"
            v-model="smscode"
            label="短信验证"
            type="number"
            maxlength="6"
            clearable
            placeholder="请输入"
            :error-message-align="inputAlign"
          >
            <van-button
              :disabled="disableSms"
              :type="smsBtnType"
              @click="openCheckCode"
              size="mini"
              plain
              slot="button"
            >
              {{ smsText || "获取验证码" }}
            </van-button>
          </van-field>
          <van-field
            :input-align="inputAlign"
            :class="`bbr${pindex}_occupationCode`"
            v-if="infoReg.hasOwnProperty('occupationCode')"
            @click="
              showPopAction('job', 'occupationCode', []);
              tipsInfo.occupationCode = '';
            "
            :value="userInfo.occupationCodeName"
            label="职业名称"
            type="textarea"
            rows="1"
            autosize
            readonly
            placeholder="请选择"
            @focus="tipsInfo.occupationCode = ''"
            :error-message="tipsInfo.occupationCode"
            :error-message-align="inputAlign"
          >
            <span class="ms-row-icon" slot="right-icon"></span>
          </van-field>
          <!-- 邮箱 -->
          <div class="van-cell extro" v-if="infoReg.hasOwnProperty('email')">
            <van-field
              :input-align="inputAlign"
              :class="`bbr${pindex}_email`"
              v-model="userInfo.email"
              @input="showEmailAppend = true"
              @blur="hideAppend"
              @focus="
                tipsInfo.email = '';
                showEmailAppend = true;
              "
              type="email"
              clearable
              placeholder="请输入"
              label-width="170px"
              :error-message="tipsInfo.email"
              :error-message-align="inputAlign"
            >
              <div slot="label" class="flexlabel">
                <span class="mr5">电子邮箱</span>
                <div
                  class="same_to_btn"
                  :class="sameAppntForEmail ? 'is_same_res' : ''"
                  @click.stop="sameToAppnt($event, 'email')"
                >
                  同投保人
                </div>
              </div>
            </van-field>
            <div class="hintBox" v-if="emails.length > 0 && showEmailAppend">
              <div
                @click="userInfo.email = mail"
                class="hintItem"
                v-for="mail in emails"
                :key="mail"
              >
                {{ mail }}
              </div>
            </div>
          </div>
          <van-field
            label="身高"
            :class="`bbr${pindex}_height`"
            v-model="userInfo.height"
            :input-align="inputAlign"
            maxlength="3"
            :formatter="formatter"
            clearable
            type="digit"
            placeholder="请输入"
            @focus="tipsInfo.height = ''"
            :error="tipsInfo.height !== ''"
            @blur="testBMI('height')"
            v-if="infoReg.hasOwnProperty('height')"
          >
            <template #button>
              <span class="field_unit">厘米(CM)</span>
            </template>
          </van-field>
          <van-field
            label="体重"
            v-model="userInfo.weight"
            maxlength="3"
            clearable
            :input-align="inputAlign"
            type="number"
            placeholder="请输入"
            @focus="tipsInfo.weight = ''"
            :formatter="formatter"
            @blur="testBMI('weight')"
            :error="tipsInfo.weight !== ''"
            v-if="infoReg.hasOwnProperty('weight')"
          >
            <template #button>
              <span class="field_unit">公斤(KG)</span>
            </template>
          </van-field>
          <!-- 社保 -->
          <van-field
            :input-align="inputAlign"
            :class="`bbr${pindex}_socialInsuFlag`"
            class="btn_pad3"
            :label="socialName"
            readonly
            @focus="tipsInfo.socialInsuFlag = ''"
            :error-message="tipsInfo.socialInsuFlag"
            :error-message-align="inputAlign"
            v-if="infoReg.hasOwnProperty('socialInsuFlag')"
          >
            <template #input>
              <MsRadio
                :curVal="userInfo.socialInsuFlag"
                btnType="socialInsuFlag"
                labelName="text"
                valueName="keyId"
                flexName="mag0"
                :arrList="socialSecList"
                @clickEvent="changeRadioInfo"
              />
            </template>
          </van-field>
          <!-- 个税说明 crsIdType  crsIdTypeName -->
          <van-field
            :class="`bbr${pindex}_crsIdType`"
            :value="userInfo.crsIdTypeName"
            @click="showPopAction('picker', 'crsIdType', crsIdTypeList)"
            readonly
            placeholder="请选择"
            :input-align="inputAlign"
            @focus="tipsInfo.crsIdType = ''"
            :error-message="tipsInfo.crsIdType"
            :error-message-align="inputAlign"
            v-if="infoReg.hasOwnProperty('crsIdType')"
          >
            <div slot="label" class="flex_ac">
              <span>税收居民类型</span>
              <FieldDescMode field="crsIdType" />
            </div>
            <span class="ms-row-icon" slot="right-icon"></span>
          </van-field>
          <!-- 证件照 -->
          <van-field
            :input-align="inputAlign"
            :class="`bbr${pindex}_frontImg`"
            label-width="120px"
            readonly
            @click="
              tipsInfo.frontImg = '';
              toOcrUpload();
            "
            :error-message="tipsInfo.frontImg"
            :error-message-align="inputAlign"
            v-if="showFrontImg"
          >
            <div slot="label" class="userSelect">
              <span>证件照上传</span>
              <FieldDescMode field="frontImg" v-if="idImgNotCheck.includes('0')" />
            </div>
            <template #input>
              <div class="flex_ac">
                {{ userInfo.frontImg ? "已上传" : "请上传" }}
                <MsImgIcon name="camera_l" size="22" style="margin-left: 5px" />
              </div>
            </template>
          </van-field>
        </div>
      </div>

      <!-- 健康告知 -->
      <van-field
        label="健康告知"
        :class="`bbr${pindex}_healthyStatus`"
        :input-align="inputAlign"
        @click="showHealthPop()"
        v-model="gzFlagName"
        readonly
        placeholder="请确定"
        :error-message="tipsInfo.healthyStatus"
        :error-message-align="inputAlign"
        @focus="tipsInfo.healthyStatus = ''"
        v-if="infoReg.hasOwnProperty('healthyStatus')"
      >
        <span class="ms-row-icon" slot="right-icon"></span>
      </van-field>
    </div>
    <van-popup
      v-model="showPop"
      overlay-class="lay1_shark"
      round
      position="bottom"
    >
      <div v-if="showPop">
        <van-picker
          v-if="popConfig.type == 'picker'"
          ref="picker"
          show-toolbar
          :columns="viewOptions"
          @confirm="onConfirmPick"
          @cancel="showPop = false"
          :default-index="defaultIndex"
        >
          <div slot="title" class="keyBox" v-if="popConfig.list.length > 8">
            <input
              type="text"
              class="keyInput"
              placeholder="请输入关键字查询"
              v-model="keyWord"
            />
          </div>
        </van-picker>
        <van-datetime-picker
          v-else-if="popConfig.type == 'date'"
          :value="currentDate"
          :min-date="minDate"
          :max-date="maxDate"
          type="date"
          @confirm="onConfirmDate"
          @cancel="showPop = false"
        />
        <OccupationPop
          v-else-if="popConfig.type == 'job'"
          @cancel="showPop = false"
          @confirm="onConfirmDJob"
        />
        <Address
          v-else-if="popConfig.type == 'address'"
          @cancle="showPop = false"
          @addresssConfirm="addresssConfirm"
        />
      </div>
    </van-popup>
    <OcrRecoganizeUpload
      :showOcrPop="showSheet"
      :ocrType="`bbr-${pindex}`"
      :ref="`bbr${pindex}UploadRef`"
      @sureBtn="sureOcrRes"
      v-if="showSheet"
    />
    <!-- 健康告知 -->
    <HealthyPop
      :ref="`bbr${pindex}gz`"
      @setValue="setHealthyStatus"
      @close="closeEvent"
      v-if="healthyPop"
    />
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import FieldDescMode from "./FieldDescMode";
import HealthyPop from "./HealthyPop";
import OcrRecoganizeUpload from "./OcrRecoganizeUpload";
import { validUserInfo } from "@/translate/validate/customer";
import { userInfoMix, bbrAndSyrInfoMix } from "@/mixins/userInfo";
import { getHealthNoticeUrl } from "@/utils/functions";

export default {
  name: "AssuredItemModule",
  components: {
    HealthyPop,
    FieldDescMode,
    OcrRecoganizeUpload,
  },
  props: {
    pindex: {
      type: [String, Number],
      default: () => 0,
    },
  },
  data() {
    return {
      enfold: true,
      userType: "被保人",
      healthyPop: false,
    };
  },
  computed: {
    ...mapGetters({
      idTypeList: "dictionary/insuredIdTypeList",
      bbrToTbrRela: "dictionary/bbrToTbrRela",
      bbrAddItemMax: "page/bbrAddItemMax",
      tbBirthStrMin: "infoReg/bbBirthMin",
      tbBirthStrMax: "infoReg/bbBirthMax",
      appnt: "insert/appnt",
      bbrList: "insert/assuredList",
    }),
    tbgxList() {
      let res = this.bbrToTbrRela;
      if (this.pindex > 0) {
        res = this.bbrToTbrRela.filter((ele) => ele.keyId != "4");
      }
      return res;
    },
    infoReg() {
      return this.inputReg.insured;
    },
    gzFlagName: {
      get() {
        let res = "";
        if (this.userInfo.healthyStatus == "Y") {
          res = "通过";
        } else if (this.userInfo.healthyStatus == "N") {
          res = "未通过";
        }
        return res;
      },
      set(val) {
        // console.log(val);
      },
    },
    getRelaToAppnt() {
      let res = "";
      if (this.userInfo.relationToAppnt) {
        res = this.userInfo.relationToAppnt;
      }
      return res;
    },
  },
  watch: {
    userInfo: {
      handler: function (val) {
        if (this.pageLoad) {
          // console.log("watch---userInfo", val);
          this.$store.commit("insert/UPDATE_ASSURED", {
            index: this.pindex,
            data: val,
          });
        }
      },
      deep: true,
    },
    // 本人，修改投保人，更新被保人
    appnt: {
      handler: function (val) {
        if (this.getRelaToAppnt == "4") {
          this.isSelfWithAppnt();
        }
      },
      deep: true,
    },
    // 切换为本人，投保人赋值被保人
    getRelaToAppnt: {
      handler: function (val) {
        if (val == "4") {
          this.isSelfWithAppnt();
        }
      },
      deep: true,
    },
  },
  mixins: [userInfoMix, bbrAndSyrInfoMix],
  created() {
    let obj = this.assuredList[this.pindex];
    this.changeData(obj);
    this.initDefaultData();
    // 投保关系初始化
    const fdObj = this.tbgxList.find(
      (ele) => ele.keyId == this.userInfo.relationToAppnt
    );
    if (!fdObj) {
      const demObj = this.tbgxList[0];
      this.changeData({
        relationToAppnt: demObj.keyId,
        relationToAppntName: demObj.text,
      });
    }
    this.pageLoad = true;
  },
  mounted() {
    this.getAutoNoticeRes();
  },
  methods: {
    openOcrPop() {
      if (this.userInfo.relationToAppnt == "4") return;
      this.showSheet = true;
    },
    isSelfWithAppnt() {
      for (const key in this.userInfo) {
        if (Object.hasOwnProperty.call(this.appnt, key)) {
          const keyValue = this.appnt[key];
          if (keyValue) {
            this.userInfo[key] = keyValue;
          }
        }
      }
      this.$forceUpdate();
    },
    getAutoNoticeRes() {
      const querys = this.$route.query;
      if (querys.uid && this.userInfo.idNum == querys.uid) {
        let flag = "Y";
        if (querys.undwrtDecideType == "A") {
          flag = "Y";
        } else if (querys.undwrtDecideType == "H") {
          flag = "N";
        } else {
          flag = querys.undwrtDecideType;
        }
        let obj = {
          healthyStatus: flag,
          uwMedicalId: querys.uwMedicalId || "",
        };
        this.sendSmartHealthy();
        // console.log("getAutoNoticeRes", obj);
        this.changeData(obj);
      }
    },
    showHealthPop() {
      if (!this.userInfo.idNum) return this.$toast("请填写客户信息");
      this.healthyPop = true;
      this.$nextTick(() => {
        this.$refs[`bbr${this.pindex}gz`].initModuleDatas(`${this.pindex}`);
      });
    },
    toOcrUpload() {
      this.showSheet = true;
      this.$nextTick(() => {
        this.$refs[`bbr${this.pindex}UploadRef`].initModule(this.userInfo);
      });
    },
    closeEvent(value) {
      this.setHealthyStatus(value);
      this.healthyPop = false;
    },
    setHealthyStatus(value) {
      if (value) {
        this.changeData({
          healthyStatus: value,
        });
      }
    },
    delUserItem() {
      this.$baseConfirm(`是否要删除该${this.userType}信息?`, () => {
        this.$store.commit("insert/DELETE_ASSURED", this.pindex);
      });
    },
    saveForm() {
      // 校验+提交
      // if (this.userInfo.relationToAppnt == "4") {
      //   Object.assign(this.userInfo, this.appnt);
      // }
      let uData = JSON.parse(JSON.stringify(this.userInfo));
      const ruleInput = JSON.parse(JSON.stringify(this.infoReg));
      let res = validUserInfo(ruleInput, uData, `${this.userType}`);
      if (res.status == false) {
        let target = document.querySelector(`.bbr${this.pindex}_${res.target}`);
        this.tipsInfo[res.target] = res.msg;
        if (target) {
          target.scrollIntoView({
            behavior: "smooth",
            block: "center",
          });
        }
        this.$toast(res.msg);
      }
      return res;
    },
    sendSmartHealthy() {
      const querys = this.$route.query;
      let params = {
        ...this.apiComParams,
        choice: "",
        idType: this.userInfo.idType || "",
        idNo: this.userInfo.idNum || "",
        uwMedicalId: querys.uwMedicalId || "",
        undwrtDecideType: querys.undwrtDecideType || "",
        successUrl: ``,
        failUrl: ``,
      };
      this.$store.commit("updateLoad", true);
      getHealthNoticeUrl(params)
        .then(({ data }) => {
          this.$store.commit("updateLoad", false);
          if (data.code == "0") {
            this.$toast(data.msg);
          }
        })
        .catch((err) => {
          this.$store.commit("updateLoad", false);
        });
    },
    watchNstatus() {
      const uids = this.$getMessage("uid_list");
      if (!uids) return;
      const curVal = `${this.userInfo.idNum}${this.userInfo.idName}`,
        cheVal = uids[this.pindex];
      if (curVal != cheVal) {
        this.changeData({
          healthyStatus: "",
        });
      }
    },
  },
};
</script>

<style lang="less" scoped>
@import "../style.less";
.topSec {
  height: 45px;
  padding: 0 12px;
}
</style>
